<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/9/2
 * Time: 13:58
 */
namespace App\Services;

use App\Repositories\CollectMoneyBillRepository;
use App\Repositories\PlatformProfitRepository;
use App\Repositories\ThreeApiErrorLogsRepository;
use App\Repositories\UserCreditCardRepository;
use App\Repositories\UserLevelPassageBankRepository;
use App\Repositories\UserLevelPassageRepository;
use App\Repositories\UserLevelRelationsRepository;
use App\Repositories\UserRepository;

class CollectMoneyProfitService extends CommonService
{
    protected $userLevelPassageRepository;
    protected $userLevelRelationsRepository;
    protected $userLevelRelationsService;
    protected $userLevelPassageBankRepository;
    protected $platformProfitRepository;
    protected $userRepository;
    protected $collectMoneyBillRepository;
    protected $threeApiErrorLogsRepository;
    protected $cloudspSMS;
    protected $messageService;
    protected $userCreditCardRepository;
    protected $userProfitService;

    public function __construct(UserLevelPassageRepository $userLevelPassageRepository,
                                UserLevelRelationsRepository $userLevelRelationsRepository,
                                UserLevelRelationsService $userLevelRelationsService,
                                UserLevelPassageBankRepository $userLevelPassageBankRepository,
                                PlatformProfitRepository $platformProfitRepository,
                                UserRepository $userRepository,
                                CollectMoneyBillRepository $collectMoneyBillRepository,
                                ThreeApiErrorLogsRepository $threeApiErrorLogsRepository,
                                CloudspSMS $cloudspSMS,
                                MessageService $messageService,
                                UserCreditCardRepository $userCreditCardRepository,
                                UserProfitService $userProfitService)
    {
        $this->userLevelPassageRepository = $userLevelPassageRepository;
        $this->userLevelRelationsRepository = $userLevelRelationsRepository;
        $this->userLevelRelationsService = $userLevelRelationsService;
        $this->userLevelPassageBankRepository = $userLevelPassageBankRepository;
        $this->platformProfitRepository = $platformProfitRepository;
        $this->userRepository = $userRepository;
        $this->collectMoneyBillRepository = $collectMoneyBillRepository;
        $this->threeApiErrorLogsRepository = $threeApiErrorLogsRepository;
        $this->cloudspSMS = $cloudspSMS;
        $this->messageService = $messageService;
        $this->userCreditCardRepository = $userCreditCardRepository;
        $this->userProfitService = $userProfitService;
    }

    /**
     * 收银分润
     * 只有代言人或服务商有收益
     * 直属代言人0.65 从属代言人0.25
     * 直属服务商0.85 从属服务商0.30
     * 当级分润金额 = 还款金额 * （当级使用费率 - 当级结算费率）* 当级分润比例
     * @param $request
     */
    public function quickMoneyNotify($param)
    {
        //更新还款状态
        if ($param['order_status'] == 'SUCCESS') {
            $this->collectMoneyProfit($param['mch_no']);
        } else {
            $failMessage = $param['fail_message'];
            $this->collectMoneyBillRepository->updateBillStatus($param['mch_no'], 6003, $failMessage);//失败
            $collectMoney = $this->collectMoneyBillRepository->findByBillSn($param['mch_no']);
            //收银金额
            $money = $collectMoney->collect_money;
            //发送收银失败消息提醒
            $user = $this->userRepository->byId($collectMoney->user_id);
            $creditCard = $this->userCreditCardRepository->byId($collectMoney->credit_card_id);
            $this->messageService->messageTemplate(4, $user->invited_code, $creditCard->bank_no, $creditCard->bank_description,
                $money, '', '', $collectMoney->id, '', '');
            //您的尾号{1}订单{2}执行失败！请重新制定计划。回T退订
//            $content = substr($repaymentPlan->bank_no, -4) . '##' . $request->dsorderid;
//            $user = $this->userRepository->byId($plan->user_id);
//            $this->cloudspSMS->sendSMSNotify($user->mobile, $content, 'failOrder', 8);
        }
        echo 'SUCCESS';
    }

    public function collectMoneyProfit($orderNo)
    {
        $collectMoney = $this->collectMoneyBillRepository->findByBillSn($orderNo);
        if ($collectMoney->collect_money_status == 6002) {
            return false;
        }
        $this->collectMoneyBillRepository->updateBillStatus($orderNo, 6002);//成功
        //收银金额
        $money = $collectMoney->collect_money;
        $passageId = $collectMoney->passage_id;
        //发送收银成功消息提醒
        $userOwn = $this->userRepository->byId($collectMoney->user_id);
        $creditCard = $this->userCreditCardRepository->byId($collectMoney->credit_card_id);
        $this->messageService->messageTemplate(3, $userOwn->invited_code, $creditCard->bank_no, $creditCard->bank_description,
            $money, '', '', $collectMoney->id, '', '');
        //手续费
        $collectMoneyServiceCharge = $collectMoney->collect_service_charge;
        //找出上两级会员
        $userLevelRelationsService = $this->userLevelRelationsService->getUserLevelRelations($collectMoney->user_id);
        $userLevelPassageThree = $this->userLevelPassageRepository->first($passageId, $userLevelRelationsService['three']['level_id']);
        $supplyPercent = 0;
        if ($userLevelPassageThree->type == 0) {
            $supplyPercent = $userLevelPassageThree->supply_percent;//成本价
        }
        if ($userLevelPassageThree->type == 1) {
            $userLevelPassageBank = $this->userLevelPassageBankRepository->passageToBank($passageId, $creditCard->bank_code, $userLevelRelationsService['three']['level_id']);
            $supplyPercent = $userLevelPassageBank->supply_percent;//成本价
        }
        $cost = round($money * $supplyPercent);//成本价
        $profit = $collectMoneyServiceCharge - $userLevelPassageThree->second_rate;
        if (!empty($userLevelRelationsService)) {
            //直接收益
            if (!empty($userLevelRelationsService['two'])) {
                if ($userLevelRelationsService['two']['level_id'] <= 2) {
                    $directProfit = $this->userProfitService->userProfit($userLevelRelationsService['two']['level_id'], $money, $userLevelPassageThree->rate,
                        3, $passageId, $creditCard->bank_code, $userOwn->mobile, $collectMoney->bill_sn, $profit, $collectMoney->user_id,
                        $userLevelRelationsService['two']['user_id'], 8, 0);
                    $directToUserId = $userLevelRelationsService['two']['user_id'];
                } else {
                    $directProfit = 0;
                    $directToUserId = 0;
                }
            } else {
                $directProfit = 0;
                $directToUserId = 0;
            }
            //间接收益
            if (!empty($userLevelRelationsService['one'])) {
                if ($userLevelRelationsService['one']['level_id'] <= 2) {
                    $indirectProfit = $this->userProfitService->userProfit($userLevelRelationsService['one']['level_id'], $money, $userLevelPassageThree->rate,
                        3, $passageId, $creditCard->bank_code, $userOwn->mobile, $collectMoney->bill_sn, $profit, $collectMoney->user_id,
                        $userLevelRelationsService['one']['user_id'], 8, 1);
                    $indirectToUserId = $userLevelRelationsService['one']['user_id'];
                } else {
                    $indirectProfit = 0;
                    $indirectToUserId = 0;
                }
            } else {
                $indirectProfit = 0;
                $indirectToUserId = 0;
            }
            //平台收益
            $platformProfit = $collectMoneyServiceCharge - $directProfit - $indirectProfit - $cost;
            $data = [
                'bill_no' => makeOrderNo(),
                'from_profit_sn' => $collectMoney->bill_sn,
                'revenue_money' => $collectMoneyServiceCharge,//手续费+秒到费
                'profit_money' => $platformProfit,//手续费+秒到费-两层级分润-成本
                'cost_money' => $cost,//成本
                'pen_num' => 1,//消费笔数
                'from_user_id' => $collectMoney->user_id,
                'direct_to_user_id' => $directToUserId,
                'direct_profit_money' => $directProfit,
                'indirect_to_user_id' => $indirectToUserId,
                'indirect_profit_money' => $indirectProfit,
                'profit_type' => 3,//收益类型： 1好友升级 2好友还款 3好友收款 4交易返现 5办理贷款 6办信用卡
                'create_time' => time(),
                'create_month' => date('Y-m'),
            ];
            $this->platformProfitRepository->create($data);
        }
        //更新单日限额
        $collectMoneyEveryDayMoneyRedisKey = $this->collectMoneyEveryDayMoneyRedisKey() .
            'user_id_' . $collectMoney->user_id . '_credit_card_id_' . $collectMoney->credit_card_id;
        if ($this->redis()->exists($collectMoneyEveryDayMoneyRedisKey)) {
            $everyDayMoney = $this->redis()->get($collectMoneyEveryDayMoneyRedisKey);
            $limitTTl = $this->redis()->ttl($collectMoneyEveryDayMoneyRedisKey);
            $money += $everyDayMoney;
            $this->redis()->setex($collectMoneyEveryDayMoneyRedisKey, $limitTTl, $money);
        } else {
            $expireTime = strtotime('23:59') - time();
            $this->redis()->setex($collectMoneyEveryDayMoneyRedisKey, $expireTime, $money);
        }
    }
}